package com.springcloudali.ms.conf;

import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;

/**
 * <h1>8位技术专家全程教学实战，全面覆盖Java进阶知识体系。<br/><br/><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">极客训练营地址：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/SpringCloudAlibabaTutorial">极客案例代码地址：https://gitee.com/ylimhhmily/SpringCloudAlibabaTutorial</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101</a></h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2023-05-14
 */
public class NacosWritableDataSource<T> implements WritableDataSource<T> {

    private String dataId;
    private String group;
    private ConfigService configService;

    public NacosWritableDataSource(String dataId,
                                   String group,
                                   String serverAddr,
                                   String namespace) throws Exception {
        this.dataId = dataId;
        this.group = group;

        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
        properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);

        configService = NacosFactory.createConfigService(properties);
    }

    @Override
    public void write(T t) throws Exception {
        configService.publishConfig(this.dataId, this.group, JSON.toJSONString(t));
    }

    @Override
    public void close() throws Exception {
    }
}
